package com.yserp.hgdz.controller;
import com.yserp.hgdz.entity.THgArdzEntity;
import com.yserp.hgdz.service.THgArdzServiceI;
import com.yserp.hgdz.page.THgArdzPage;
import com.yserp.hgdz.entity.THgArdzAEntity;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yserp.wzyw.entity.TWzCkHeadEntity;
import com.yserp.wzyw.entity.TWzCkItemEntity;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecgframework.core.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.GsonUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller
 * @Description: 应收对账单
 * @author onlineGenerator
 * @date 2018-06-18 18:21:37
 * @version V1.0   
 *
 */
@Api(value="THgArdz",description="应收对账单",tags="tHgArdzController")
@Controller
@RequestMapping("/tHgArdzController")
public class THgArdzController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(THgArdzController.class);

	@Autowired
	private THgArdzServiceI tHgArdzService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	/**
	 * 应收对账单列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/yserp/hgdz/tHgArdzList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(THgArdzEntity tHgArdz,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(THgArdzEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tHgArdz);
		try{
		//自定义追加查询条件
		String query_docdate_begin = request.getParameter("docdate_begin");
		String query_docdate_end = request.getParameter("docdate_end");
		if(StringUtil.isNotEmpty(query_docdate_begin)){
			cq.ge("docdate", new SimpleDateFormat("yyyy-MM-dd").parse(query_docdate_begin));
		}
		if(StringUtil.isNotEmpty(query_docdate_end)){
			cq.le("docdate", new SimpleDateFormat("yyyy-MM-dd").parse(query_docdate_end));
		}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tHgArdzService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除应收对账单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(THgArdzEntity tHgArdz, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		tHgArdz = systemService.getEntity(THgArdzEntity.class, tHgArdz.getId());
		String message = "应收对账单删除成功";
		try{
			tHgArdzService.delMain(tHgArdz);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "应收对账单删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除应收对账单
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String message = "应收对账单删除成功";
		try{
			for(String id:ids.split(",")){
				THgArdzEntity tHgArdz = systemService.getEntity(THgArdzEntity.class,
				id
				);
				tHgArdzService.delMain(tHgArdz);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "应收对账单删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}



	@RequestMapping(params = "doPrint")
	@ResponseBody
	public void downReceiveExcel(String id,
								 HttpServletRequest request, HttpServletResponse response) {
		OutputStream fileOut = null;
		BufferedImage bufferImg = null;
		String codedFileName = null;
		THgArdzEntity THgArdz = systemService.getEntity(THgArdzEntity.class,
				id);// 获取抬头
		String hql0 = "from THgArdzAEntity where 1 = 1 AND dZID = ? ";
		List<THgArdzAEntity> tHgArdzAOldList = systemService.findHql(hql0,id);
		try {
			StringBuffer sber = new StringBuffer();

			ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

			// 进行转码，使其支持中文文件名
			codedFileName = java.net.URLEncoder.encode("中文", "UTF-8");
			response.setHeader("content-disposition", "attachment;filename="
					+ THgArdz.getCardname()+DateUtils.date2Str(THgArdz.getDocdate(),DateUtils.date_sdf) + ".xls");

			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("应收对账单");
			sheet.setMargin(HSSFSheet.TopMargin,0.1);// 页边距（上）
			sheet.setMargin(HSSFSheet.BottomMargin,0.1);// 页边距（下）
			sheet.setMargin(HSSFSheet.LeftMargin,0.1);// 页边距（左）
			sheet.setMargin(HSSFSheet.RightMargin,0.0);// 页边距（右
			sheet.setColumnWidth(0, 16 * 256);
			sheet.setColumnWidth(1, 15 * 256);
			sheet.setColumnWidth(2, 10 * 200);
			sheet.setColumnWidth(3, 15 * 256);
			sheet.setColumnWidth(4, 10 * 256);
			sheet.setColumnWidth(5, 22 * 256);
			 sheet.setColumnWidth(6, 10 * 256);
			sheet.setColumnWidth(7, 10 * 256);
			sheet.setColumnWidth(8, 10 * 256);
			sheet.setColumnWidth(9, 13 * 256);
			sheet.setColumnWidth(10, 10 * 256);
			sheet.setColumnWidth(11, 10 * 256);
			// 创建第一行
			Row row = sheet.createRow((short) 0); // 第一行空白

			// 创建两种单元格格式
			CellStyle cs = wb.createCellStyle();
			CellStyle cs2 = wb.createCellStyle();
			CellStyle cs3 = wb.createCellStyle();
			CellStyle cs4 = wb.createCellStyle();
			CellStyle cs5 = wb.createCellStyle();
			// 创建两种字体
			Font f = wb.createFont();
			Font f2 = wb.createFont();

			// 创建第一种字体样式（用于列名）
			f.setFontHeightInPoints((short) 22);
			f.setColor(IndexedColors.BLACK.getIndex());
			f.setBoldweight(Font.BOLDWEIGHT_BOLD);

			// 创建第二种字体样式（用于值）
			f2.setFontHeightInPoints((short) 16);
			f2.setColor(IndexedColors.BLACK.getIndex());

			// Font f3=wb.createFont();
			// f3.setFontHeightInPoints((short) 10);
			// f3.setColor(IndexedColors.RED.getIndex());

			// 设置第一种单元格的样式（用于列名）
			cs.setFont(f);
			cs.setBorderLeft(CellStyle.BORDER_NONE);
			cs.setBorderRight(CellStyle.BORDER_NONE);
			cs.setBorderTop(CellStyle.BORDER_NONE);
			cs.setBorderBottom(CellStyle.BORDER_NONE);
			cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			// 设置第二种单元格的样式（用于值）
			cs2.setFont(f2);
			cs2.setBorderLeft(CellStyle.BORDER_NONE);
			cs2.setBorderRight(CellStyle.BORDER_NONE);
			cs2.setBorderTop(CellStyle.BORDER_NONE);
			cs2.setBorderBottom(CellStyle.BORDER_NONE);
			cs2.setWrapText(true);

			// cs2.setAlignment(CellStyle.BORDER_NONE);

			cs3.setFont(f2);
			cs3.setBorderLeft(CellStyle.BORDER_THIN);
			cs3.setBorderRight(CellStyle.BORDER_THIN);
			cs3.setBorderTop(CellStyle.BORDER_THIN);
			cs3.setBorderBottom(CellStyle.BORDER_THIN);
			// cs3.setAlignment(CellStyle.BORDER_HAIR);
			cs4.setFont(f2);
			cs4.setBorderTop(CellStyle.BORDER_MEDIUM);
			cs4.setBorderBottom(CellStyle.BORDER_MEDIUM);

			cs5.setFont(f2);
			cs5.setBorderLeft(CellStyle.BORDER_NONE);
			cs5.setBorderRight(CellStyle.BORDER_NONE);
			cs5.setBorderTop(CellStyle.BORDER_NONE);
			cs5.setBorderBottom(CellStyle.BORDER_NONE);
//			cs5.setWrapText(true);

			Row row1 = sheet.createRow((short) 1); // 第二行标题
			row1.setHeight((short) 700);
			Cell cellTitle = row1.createCell(0);
			cellTitle.setCellValue(ResourceUtil.getConfigByName("comname")+"应收对账单");
			cellTitle.setCellStyle(cs);
			Row rowHead1 = sheet.createRow((short) 2); // 头部第一行
			rowHead1.setHeight((short) 800);
			Cell cellHead11 = rowHead1.createCell(0);
			cellHead11.setCellValue("对账日期：" + DateUtils.date2Str(THgArdz.getDocdate(),DateUtils.date_sdf));
			cellHead11.setCellStyle(cs2);
			Cell cellHead12 = rowHead1.createCell(7);

			cellHead12.setCellValue("客户：" + THgArdz.getCardname());
			cellHead12.setCellStyle(cs2);


			Row rowHead2 = sheet.createRow((short) 2); // 头部第二行
			rowHead2.setHeight((short) 500);
			Cell cellHead21 = rowHead2.createCell(0);
			cellHead21.setCellValue("审批状态：" + THgArdz.getDocstatus());
			cellHead21.setCellStyle(cs2);


//			Row cellHead23 = sheet.createRow((short) 3); // 头部第二行
			rowHead2.setHeight((short) 500);
			Cell cellHead22 = rowHead2.createCell(7);
			cellHead22.setCellValue("备注：" + THgArdz.getComment());
			cellHead22.setCellStyle(cs2);

//			Cell cellHead23 = rowHead2.createCell(2);
//			cellHead23.setCellValue("部门名称：" + tWzCkHead.getOrgName());
//			cellHead23.setCellStyle(cs2);

//			Row rowHead3 = sheet.createRow((short) 4); // 头部第三行
//			rowHead3.setHeight((short) 500);
//			Cell cellHead31 = rowHead3.createCell(0);
//			cellHead31.setCellValue("领用人：" + tWzCkHead.getCkUsername()
//			);
//			cellHead31.setCellStyle(cs2);
//
//			Cell cellHead35 = rowHead3.createCell(2);
//			cellHead35.setCellValue("姓名：" + tWzCkHead.getCkName());
//			cellHead35.setCellStyle(cs2);

			// 合并单元格
			CellRangeAddress c = new CellRangeAddress(0, 0, 0, 11); // 第一行空白
			CellRangeAddress c0 = new CellRangeAddress(1, 1, 0, 11);// 第二行标题

			CellRangeAddress c1 = new CellRangeAddress(2, 2, 0, 6);// 第三行通知单号
			CellRangeAddress c11 = new CellRangeAddress(2, 2, 7, 11);// 第三行通知单号
			CellRangeAddress c2 = new CellRangeAddress(3, 3, 0, 11);// 第四行客户
//			CellRangeAddress c3 = new CellRangeAddress(3, 3, 2, 5);// 第四行客户送货时间
//			CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);// 第五行客户
//			CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 5);// 第五行客户送货时间
			// CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);
			// CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 3);
			// CellRangeAddress c6 = new CellRangeAddress(4, 4, 4, 5);
			// CellRangeAddress c7 = new CellRangeAddress(4, 4, 6, 6);

			sheet.addMergedRegion(c);
			sheet.addMergedRegion(c0);

			sheet.addMergedRegion(c1);
			sheet.addMergedRegion(c11);

			sheet.addMergedRegion(c2);
//			sheet.addMergedRegion(c3);
//			sheet.addMergedRegion(c4);
//			sheet.addMergedRegion(c5);

			// sheet.addMergedRegion(c7);

			Row rowColumnName = sheet.createRow((short) 5); // 列名
			rowColumnName.setHeight((short) 500);
			String[] columnNames = { "日期", "经营单位", "件数", "报关单号", "仓库",
					"进仓编号/提单号","续单", "报关费", "查验费",
					"其他代垫","合计",
					"备注" };

			for (int i = 0; i < columnNames.length; i++) {
				Cell cell = rowColumnName.createCell(i);
				cell.setCellValue(columnNames[i]);
				cell.setCellStyle(cs3);
			}
			int cellsNum = 5;
			int cerconNo = 1;
			BigDecimal allsum = new BigDecimal("0");
			for (int i = 0; i < tHgArdzAOldList.size(); i++) {
				BigDecimal rowsum = new BigDecimal("0");
				THgArdzAEntity entity = tHgArdzAOldList.get(i);
				cellsNum++;
				Row rowColumnValue = sheet.createRow((short) cellsNum); // 列名
				rowColumnValue.setHeight((short) 400);

				Cell cell2 = rowColumnValue.createCell(0);


				try {
					cell2.setCellStyle(cs3);
					cell2.setCellValue(DateUtils.date2Str(entity.getRq(),DateUtils.date_sdf));
				}catch (Exception e){

				}
				try {
					Cell cell3 = rowColumnValue.createCell(1);
					cell3.setCellValue(entity.getCardname());
					cell3.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell4 = rowColumnValue.createCell(2);
					cell4.setCellValue(entity.getJs());
					cell4.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell5 = rowColumnValue.createCell(3);
					cell5.setCellValue(entity.getBgdh());
					cell5.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {


					Cell cell6 = rowColumnValue.createCell(4);
					cell6.setCellValue(entity.getWhscode());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}

				try {


					Cell cell6 = rowColumnValue.createCell(5);
					cell6.setCellValue(entity.getTdh());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {


					Cell cell6 = rowColumnValue.createCell(6);
					cell6.setCellValue(entity.getXdfee());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {


					Cell cell6 = rowColumnValue.createCell(7);
					cell6.setCellValue(entity.getHgfee());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {


					Cell cell6 = rowColumnValue.createCell(8);
					cell6.setCellValue(entity.getCyfee());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {


					Cell cell6 = rowColumnValue.createCell(9);
					cell6.setCellValue(entity.getQtfee());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}

				try{
					rowsum = rowsum.add(new BigDecimal(entity.getXdfee()));
				}catch (Exception e){

				}
				try{
					rowsum = rowsum.add(new BigDecimal(entity.getHgfee()));
				}catch (Exception e){

				}
				try{
					rowsum = rowsum.add(new BigDecimal(entity.getCyfee()));
				}catch (Exception e){

				}
				try{
					rowsum = rowsum.add(new BigDecimal(entity.getQtfee()));
				}catch (Exception e){

				}
				try {


					Cell cell6 = rowColumnValue.createCell(10);
					cell6.setCellValue(rowsum.toString());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}

				try {


					Cell cell6 = rowColumnValue.createCell(11);
					cell6.setCellValue(entity.getComment());
					cell6.setCellStyle(cs3);
				}catch (Exception e){

				}
				try{
					allsum = allsum.add(rowsum) ;

				}catch (Exception e){

				}
				cerconNo++;
			}
			cellsNum++;
			Row rowColumnInfosum = sheet.createRow((short) 1+cellsNum); // 列名
			Cell cellrowsum = rowColumnInfosum.createCell(0);
			cellrowsum.setCellValue("合计");
			cellrowsum.setCellStyle(cs5);
			Cell cellrowsumvalue = rowColumnInfosum.createCell(10);
			try{
				cellrowsumvalue.setCellValue(allsum.toString());

			}catch (Exception e){

			}
			cellrowsumvalue.setCellStyle(cs5);

			Row rowColumnInfo0 = sheet.createRow((short) 2 + cellsNum); // 列名
			Cell cellrow0 = rowColumnInfo0.createCell(0);
			cellrow0.setCellValue(ResourceUtil.getConfigByName("comcomment"));
			cellrow0.setCellStyle(cs5);
			Row rowColumnInfo1 = sheet.createRow((short) 4 + cellsNum); // 列名
			Cell cellrow1 = rowColumnInfo1.createCell(0);
			cellrow1.setCellValue(ResourceUtil.getConfigByName("comfiname"));
			cellrow1.setCellStyle(cs5);
			Row rowColumnInfo2 = sheet.createRow((short) 5 + cellsNum); // 列名
			Cell cellrow2 = rowColumnInfo2.createCell(0);
			cellrow2.setCellValue(ResourceUtil.getConfigByName("comfibankname"));
			cellrow2.setCellStyle(cs5);
			Row rowColumnInfo3 = sheet.createRow((short) 6 + cellsNum); // 列名
			Cell cellrow3 = rowColumnInfo3.createCell(0);
			cellrow3.setCellValue(ResourceUtil.getConfigByName("comfibankid"));
			cellrow3.setCellStyle(cs5);
			Row rowColumnInfo4 = sheet.createRow((short) 7 + cellsNum); // 列名
			Cell cellrow4 = rowColumnInfo4.createCell(0);
			cellrow4.setCellValue(ResourceUtil.getConfigByName("comfitel"));
			cellrow4.setCellStyle(cs5);
			Row rowColumnInfo5 = sheet.createRow((short) 8 + cellsNum); // 列名
			Cell cellrow5 = rowColumnInfo5.createCell(0);
			cellrow5.setCellValue(ResourceUtil.getConfigByName("comfiaddr"));
			cellrow5.setCellStyle(cs5);
//			rowColumnInfo.createCell(0).setCellValue(
//					"领用人：                       仓管：                     主管：                      ");
//			CellRangeAddress c15 = new CellRangeAddress(10 + cellsNum,
//					10 + cellsNum, 0, 5);
//			sheet.addMergedRegion(c15);
			fileOut = response.getOutputStream();
			HSSFPrintSetup printSetup = sheet.getPrintSetup();
			printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
			printSetup.setLandscape(true);
			wb.write(fileOut);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileOut != null) {
				try {
					fileOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}




	/**
	 * 添加应收对账单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(THgArdzEntity tHgArdz,THgArdzPage tHgArdzPage, HttpServletRequest request) {
		List<THgArdzAEntity> tHgArdzAList =  tHgArdzPage.getTHgArdzAList();
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try{
			tHgArdzService.addMain(tHgArdz, tHgArdzAList);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "应收对账单添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 更新应收对账单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(THgArdzEntity tHgArdz,THgArdzPage tHgArdzPage, HttpServletRequest request) {
		List<THgArdzAEntity> tHgArdzAList =  tHgArdzPage.getTHgArdzAList();
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try{
			tHgArdzService.updateMain(tHgArdz, tHgArdzAList);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "更新应收对账单失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 应收对账单新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(THgArdzEntity tHgArdz, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tHgArdz.getId())) {
			tHgArdz = tHgArdzService.getEntity(THgArdzEntity.class, tHgArdz.getId());
			req.setAttribute("tHgArdzPage", tHgArdz);
		}
		return new ModelAndView("com/yserp/hgdz/tHgArdz-add");
	}
	
	/**
	 * 应收对账单编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(THgArdzEntity tHgArdz, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tHgArdz.getId())) {
			tHgArdz = tHgArdzService.getEntity(THgArdzEntity.class, tHgArdz.getId());
			req.setAttribute("tHgArdzPage", tHgArdz);
		}
		return new ModelAndView("com/yserp/hgdz/tHgArdz-update");
	}
	
	
	/**
	 * 加载明细列表[对账明细]
	 * 
	 * @return
	 */
	@RequestMapping(params = "tHgArdzAList")
	public ModelAndView tHgArdzAList(THgArdzEntity tHgArdz, HttpServletRequest req) {
	
		//===================================================================================
		//获取参数
		Object id0 = tHgArdz.getId();
		//===================================================================================
		//查询-对账明细
	    String hql0 = "from THgArdzAEntity where 1 = 1 AND dZID = ? ";
	    try{
	    	List<THgArdzAEntity> tHgArdzAEntityList = systemService.findHql(hql0,id0);
			req.setAttribute("tHgArdzAList", tHgArdzAEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/yserp/hgdz/tHgArdzAList");
	}

    /**
    * 导出excel
    *
    * @param request
    * @param response
    */
    @RequestMapping(params = "exportXls")
    public String exportXls(THgArdzEntity tHgArdz,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) {
    	CriteriaQuery cq = new CriteriaQuery(THgArdzEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tHgArdz);
    	try{
    	//自定义追加查询条件
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<THgArdzEntity> list=this.tHgArdzService.getListByCriteriaQuery(cq, false);
    	List<THgArdzPage> pageList=new ArrayList<THgArdzPage>();
        if(list!=null&&list.size()>0){
        	for(THgArdzEntity entity:list){
        		try{
        		THgArdzPage page=new THgArdzPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
            	    Object id0 = entity.getId();
				    String hql0 = "from THgArdzAEntity where 1 = 1 AND dZID = ? ";
        	        List<THgArdzAEntity> tHgArdzAEntityList = systemService.findHql(hql0,id0);
            		page.setTHgArdzAList(tHgArdzAEntityList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
        map.put(NormalExcelConstants.FILE_NAME,"应收对账单");
        map.put(NormalExcelConstants.CLASS,THgArdzPage.class);
        map.put(NormalExcelConstants.PARAMS,new ExportParams("应收对账单列表", "导出人:Jeecg",
            "导出信息"));
        map.put(NormalExcelConstants.DATA_LIST,pageList);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

    /**
	 * 通过excel导入数据
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<THgArdzPage> list =  ExcelImportUtil.importExcel(file.getInputStream(), THgArdzPage.class, params);
				THgArdzEntity entity1=null;
				for (THgArdzPage page : list) {
					entity1=new THgArdzEntity();
					MyBeanUtils.copyBeanNotNull2Bean(page,entity1);
		            tHgArdzService.addMain(entity1, page.getTHgArdzAList());
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			}
			return j;
	}
	/**
	* 导出excel 使模板
	*/
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ModelMap map) {
		map.put(NormalExcelConstants.FILE_NAME,"应收对账单");
		map.put(NormalExcelConstants.CLASS,THgArdzPage.class);
		map.put(NormalExcelConstants.PARAMS,new ExportParams("应收对账单列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),
		"导出信息"));
		map.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	* 导入功能跳转
	*
	* @return
	*/
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "tHgArdzController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

 	
 	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="应收对账单列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<THgArdzPage>> list() {
		List<THgArdzEntity> list= tHgArdzService.getList(THgArdzEntity.class);
    	List<THgArdzPage> pageList=new ArrayList<THgArdzPage>();
        if(list!=null&&list.size()>0){
        	for(THgArdzEntity entity:list){
        		try{
        			THgArdzPage page=new THgArdzPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
					Object id0 = entity.getId();
				     String hql0 = "from THgArdzAEntity where 1 = 1 AND dZID = ? ";
	    			List<THgArdzAEntity> tHgArdzAOldList = this.tHgArdzService.findHql(hql0,id0);
            		page.setTHgArdzAList(tHgArdzAOldList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
		return Result.success(pageList);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取应收对账单信息",notes="根据ID获取应收对账单信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		THgArdzEntity task = tHgArdzService.get(THgArdzEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取应收对账单信息为空");
		}
		THgArdzPage page = new THgArdzPage();
		try {
			MyBeanUtils.copyBeanNotNull2Bean(task, page);
				Object id0 = task.getId();
		    String hql0 = "from THgArdzAEntity where 1 = 1 AND dZID = ? ";
			List<THgArdzAEntity> tHgArdzAOldList = this.tHgArdzService.findHql(hql0,id0);
    		page.setTHgArdzAList(tHgArdzAOldList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.success(page);
	}
 	
 	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建应收对账单")
	public ResponseMessage<?> create(@ApiParam(name="应收对账单对象")@RequestBody THgArdzPage tHgArdzPage, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<THgArdzPage>> failures = validator.validate(tHgArdzPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		List<THgArdzAEntity> tHgArdzAList =  tHgArdzPage.getTHgArdzAList();
		
		THgArdzEntity tHgArdz = new THgArdzEntity();
		try{
			MyBeanUtils.copyBeanNotNull2Bean(tHgArdzPage,tHgArdz);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("保存应收对账单失败");
        }
		tHgArdzService.addMain(tHgArdz, tHgArdzAList);

		return Result.success(tHgArdz);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新应收对账单",notes="更新应收对账单")
	public ResponseMessage<?> update(@RequestBody THgArdzPage tHgArdzPage) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<THgArdzPage>> failures = validator.validate(tHgArdzPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		List<THgArdzAEntity> tHgArdzAList =  tHgArdzPage.getTHgArdzAList();
		
		THgArdzEntity tHgArdz = new THgArdzEntity();
		try{
			MyBeanUtils.copyBeanNotNull2Bean(tHgArdzPage,tHgArdz);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("应收对账单更新失败");
        }
		tHgArdzService.updateMain(tHgArdz, tHgArdzAList);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除应收对账单")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			THgArdzEntity tHgArdz = tHgArdzService.get(THgArdzEntity.class, id);
			tHgArdzService.delMain(tHgArdz);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("应收对账单删除失败");
		}

		return Result.success();
	}
}
